﻿package com.scn.base.util;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.ResultSetMetaData;  
import java.sql.SQLException;  
  
  
  
/** 
 * 数据库工具类 
 *  
 * @author onedear 
 * @data:2010-10-21 下午06:12:39 
 */  
public class DBUtil {  
  
    public static final int SQLSERVER = 1;  
    public static final int MYSQL = 2;  
    public static final int ORACLE = 3;  
    private static final String LINE = "\r\n";  
    private static final String TAB = "\t";  
  
    /** 
     * 用于调试,懒得写相应的参数 
     *  
     * @return 
     * @throws SQLException  
     * @throws ClassNotFoundException  
     */  
    public static Connection getConnection() throws ClassNotFoundException, SQLException {  
            return getConnection("localhost:3306", "oms2012", "root",  
                    "gaoxiong", DBUtil.MYSQL);  
    }  
  
    /** 
     *  
     * 通过jdbc获取相应的数据库链接connection 
     *  
     * @param ipport 
     *            ip+port ,eg.: 192.168.0.161:1997 
     * @param dbName 
     *            databaseName ,eg. : ETForMonitor_V2 
     * @param username 
     *            eg.:sa 
     * @param password 
     *            eg. :password 
     * @param type 
     *            请看本类的静态变量 
     * @return 
     * @throws ClassNotFoundException 
     * @throws SQLException 
     */  
    public static Connection getConnection(String ipport, String dbName,  
            String username, String password, int type)  
            throws ClassNotFoundException, SQLException {  
        String jdbcString = null;  
        if (type == SQLSERVER) {  
            jdbcString = "jdbc:jtds:sqlserver://" + ipport + ";databaseName="  
                    + dbName;  
            Class.forName("net.sourceforge.jtds.jdbc.Driver");  
        } else if (type == MYSQL) {  
            jdbcString = "jdbc:mysql://" + ipport + "/" + dbName;  
            Class.forName("com.mysql.jdbc.Driver");  
        } else if (type == ORACLE) {  
            jdbcString = "jdbc:oracle:thin:@" + ipport + ":" + dbName;  
            Class.forName("oracle.jdbc.driver.OracleDriver");  
        }  
  
        Connection connection = null;  
        connection = DriverManager  
                .getConnection(jdbcString, username, password);  
        return connection;  
    }  
  
    /** 
     * 数据库表生成相应的java类，生成规则 
     * 类名=      表名（第一个字母大写） 
     * 属性名=   数据库列名 
     * get/set方法 = 根据标准生成 
     * 其中生成的基本类型均为包装类，例如Integer , Long , Boolean , String   
     * @param connection 
     * @param tableName 
     * @param dbType 
     * @param path 
     * @param isCreateFile 
     * @return 
     * @throws SQLException 
     */  
    public static String table2pojo(Connection connection, String tableName,  
            int dbType, String path , boolean isCreateFile) throws SQLException {  
        String sql = "select * from " + tableName + " where 1 <> 1";  
        PreparedStatement ps = null;  
        ResultSet rs = null;  
        ps = connection.prepareStatement(sql);  
        rs = ps.executeQuery();  
        ResultSetMetaData md = rs.getMetaData();  
        int columnCount = md.getColumnCount();  
          
        StringBuffer sb = new StringBuffer();  
        sb.append("package com.scn.base.domain;");
        sb.append(LINE);
        sb.append("import java.util.Date;");  
        sb.append(LINE);
        tableName = tableName.substring(0, 1).toUpperCase() +tableName.subSequence(1, tableName.length());  
        String[] tempTables=tableName.split("\\_");
    	String tablename="";
    	for(String temp:tempTables){
    		tablename+=temp.substring(0, 1).toUpperCase()  
            + temp.substring(1, temp.length());
    	}
        sb.append("public class " + tablename + " {");  
        sb.append(LINE);
        
  
        for (int i = 1; i <= columnCount; i++) { 
        	String[] temps=md.getColumnName(i).split("\\_");
        	String column="";
        	for(String temp:temps){
        		column+=temp.substring(0, 1).toUpperCase()  
                + temp.substring(1, temp.length());
        	}
            sb.append(TAB);  
            sb.append("private "  
                    + DataBaseType.getPojoType(md.getColumnTypeName(i)) + " "  
                    + column.substring(0, 1).toLowerCase()  
                    + column.substring(1, column.length()) + ";");  
            // System.out.println("name : " + md.getColumnName(i) +  
            // "   , type :"  
            // + md.getColumnTypeName(i));  
            sb.append(LINE);  
        }  
  
        for (int i = 1; i <= columnCount; i++) {  
            sb.append(TAB);  
  
            String pojoType = DataBaseType.getPojoType(md.getColumnTypeName(i));  
            String columnName = md.getColumnName(i);  
            String getName = null;  
            String setName = null;  
            String column="";
            if (columnName.length() > 1) {  
            	String[] temps=columnName.split("\\_");
            	for(String temp:temps){
            		column+=temp.substring(0, 1).toUpperCase()  
                    + temp.substring(1, temp.length());
            	}
                getName = "public "+pojoType+" get" + column + "() {";  
                setName = "public void set" + column + "("  
                        + pojoType + " " + column.substring(0, 1).toLowerCase()  
                        + column.substring(1, column.length()) + ") {";  
            } else {  
                getName = "public get" + columnName.toUpperCase() + "() {";  
                setName = "public set" + columnName.toUpperCase() + "(" + pojoType  
                        + " " + columnName + ") {";  
            }  
              
            sb.append(LINE).append(TAB).append(getName);  
            sb.append(LINE).append(TAB).append(TAB);  
            sb.append("return " + column.substring(0, 1).toLowerCase()  
                    + column.substring(1, column.length()) +";");  
            sb.append(LINE).append(TAB).append("}");  
            sb.append(LINE);  
            sb.append(LINE).append(TAB).append(setName);  
            sb.append(LINE).append(TAB).append(TAB);  
            sb.append("this." +  column.substring(0, 1).toLowerCase()  
                    + column.substring(1, column.length()) + " = " + column.substring(0, 1).toLowerCase()  
                    + column.substring(1, column.length()) +";" );  
            sb.append(LINE).append(TAB).append("}");  
            sb.append(LINE);  
              
        }  
        sb.append("}");  
  
        System.out.println(sb.toString());  
          
        if(isCreateFile) {
        	try {
				BufferedWriter bw=new BufferedWriter(new FileWriter("F:\\work\\OMS2012\\src\\com\\scn\\base\\domain\\"+tablename+".java"));
				bw.write(sb.toString());
				bw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
         //   FileUtils.stringToFile(null,tableName +".java" , sb.toString());  
        return null;  
    }  
   
    public static void main(String[] args) throws SQLException, ClassNotFoundException {  
        Connection con = getConnection(); 
        
        
        table2pojo(con, "sys_func", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_menu", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_menu_func", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_parameter", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_role", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_role_power", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "sys_user", DBUtil.MYSQL, "" , true); 
        table2pojo(con, "user_power", DBUtil.MYSQL, "" , true); 
         
          
    }  
  
  
}  